package com.hsgene.product.service.impl;

import com.hsgene.common.ClientType;
import com.hsgene.common.util.qiniu.QiniuCertificateUtil;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.coupon.dto.GeneticDiscountDto;
import com.hsgene.product.applets.dto.AppletsGoodsCommentInfoDto;
import com.hsgene.product.applets.dto.AppletsGoodsDetailsInfoDto;
import com.hsgene.product.applets.dto.GoodsCommentListInfoDto;
import com.hsgene.product.persistence.AppletsGoodsRepository;
import com.hsgene.product.service.AppletsGoodsService;
import com.hsgene.product.service.api.DiscountCouponService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 小程序商品详情service
 *
 * @author wxf
 * @date 2018/10/11 14:59
 **/
@Service
public class AppletsGoodsServiceImpl implements AppletsGoodsService {

    @Resource
    private AppletsGoodsRepository appletsGoodsRepository;

    @Resource
    private DiscountCouponService discountCouponService;

    /**
     * 商品详情
     *
     * @param packageId 商品id
     * @param userId    用户id
     * @return
     */
    @Override
    public AppletsGoodsDetailsInfoDto getGoodsDetails(String packageId, String userId) {
        AppletsGoodsDetailsInfoDto detailsInfoDto = appletsGoodsRepository.getGoodsDetails(packageId);
        if (detailsInfoDto == null) {
            return null;
        }
        //查询详情时,更新套餐浏览次数
        appletsGoodsRepository.updatePackageScanCount(packageId);
        //图文详情图片七牛获取
        String imageDetails = detailsInfoDto.getGoodsImageDetails();
        if (StringUtils.isNotEmpty(imageDetails)) {
            String result = QiniuCertificateUtil.getDownloadCertificateStr(imageDetails);
            detailsInfoDto.setGoodsImageDetails(StringUtils.isEmpty(result) ? imageDetails : result);
        }
        //商品图片地址
        String imageUrl = detailsInfoDto.getImageUrl();
        if (StringUtils.isNotEmpty(imageUrl)) {
            String result = QiniuCertificateUtil.getDownloadCertificateStr(imageUrl);
            detailsInfoDto.setImageUrl(StringUtils.isEmpty(result) ? imageUrl : result);
        }
        //优惠券
        ApiResult<List<GeneticDiscountDto>> apiResultDiscount = discountCouponService.queryEffectiveDiscount
                (ClientType.APPLETS.getCode(), userId);
        if (apiResultDiscount.isSucc()) {
            List<GeneticDiscountDto> discountDtoList = apiResultDiscount.getData();
            if (discountDtoList != null && !CollectionUtils.isEmpty(discountDtoList)) {
                detailsInfoDto.setDiscountInfoDtos(discountDtoList.stream()
                        .filter(coupon -> coupon.getConditionPrice().compareTo(BigDecimal.valueOf(detailsInfoDto.getShowPrice())) <= 0)
                        .collect(Collectors.toList())
                );
            }
        }
        //获取最大优惠额度
        Double maxDiscountPrice = appletsGoodsRepository.getMaxDiscountPrice(detailsInfoDto.getShowPrice(), userId);
        detailsInfoDto.setMaxDiscountPrice(maxDiscountPrice);
        //评论信息
        List<AppletsGoodsCommentInfoDto> commentInfoDtos = appletsGoodsRepository.getGoodsCommentInfo(packageId,
                null, 0,
                2);
        if (commentInfoDtos == null) {
            commentInfoDtos = new ArrayList<>();
        }
        //评论图片
        commentInfoDtos.stream().forEach(infoDto -> {
            String image = infoDto.getImagesUrl();
            String result = QiniuCertificateUtil.getDownloadCertificateStr(image);
            infoDto.setImagesUrl(StringUtils.isEmpty(result) ? image : result);
        });
        detailsInfoDto.setCommentInfoDtos(commentInfoDtos);
        //获取评论总数
        Integer sumCount = appletsGoodsRepository.getCommentSumCount(packageId);
        if (sumCount == null) {
            return detailsInfoDto;
        }
        detailsInfoDto.setCommitCount(sumCount);
        return detailsInfoDto;
    }

    /**
     * 商品评论列表
     *
     * @param page    page
     * @param goodsId 商品id
     * @param size
     * @return
     */
    @Override
    public GoodsCommentListInfoDto getAllCommitInfo(String goodsId, Integer page, Integer size) {
        //评论信息
        List<AppletsGoodsCommentInfoDto> commentInfoDtos = appletsGoodsRepository.getGoodsCommentInfo(goodsId, null,
                (page - 1) * size, size);
        //获取好评、差评、中评、有图
        GoodsCommentListInfoDto listInfoDto = appletsGoodsRepository.getCommentLabel(goodsId);
        if (listInfoDto != null && commentInfoDtos != null && !commentInfoDtos.isEmpty()) {
            listInfoDto.setCommentInfoDtos(commentInfoDtos);
            //评价详情图片
            commentInfoDtos.stream().forEach(commentInfoDto -> {
                String imageUrl = commentInfoDto.getImagesUrl();
                String result = QiniuCertificateUtil.getDownloadCertificateStr(imageUrl);
                commentInfoDto.setImagesUrl(StringUtils.isEmpty(result) ? imageUrl : result);
            });
            int sumCount = listInfoDto.getAllSumCount();
            listInfoDto.setTotalPage(sumCount <= size ? 1 : sumCount / size);
        }
        return listInfoDto;
    }

    /**
     * 获取指定类型标签的评论
     *
     * @param goodsId 商品id
     * @param label   标签类型
     * @param page    分页
     * @param size
     * @return
     */
    @Override
    public List<AppletsGoodsCommentInfoDto> getLabelTypeCommit(String goodsId, Integer label, Integer page, Integer
            size) {
        List<AppletsGoodsCommentInfoDto> commentInfoDtos = appletsGoodsRepository.getGoodsCommentInfo(goodsId,
                label, (page - 1) * 10, 10);
        return commentInfoDtos;
    }

    /**
     * 获取优惠券信息
     *
     * @param discountId 优惠券id
     * @param userId     用户id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public String getGoodsDiscount(String discountId, String userId) {
        //判断是否已存在
        Integer flag = appletsGoodsRepository.checkIsExistsDiscount(discountId, userId);
        if (flag != null) {
            return "优惠券已存在";
        }
        appletsGoodsRepository.addGoodsDiscount(discountId, userId, new Date());
        return null;
    }
}
